package org.hu.controller;

import org.hu.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 部门管理
 * @author Htrees
 */
@Controller
@RequestMapping("/admin")
public class DepartmentController {
    @Autowired
    DepartmentService departmentService;

    /**
     * 展示所有部门
     * @param model
     * @return departments
     */
    @RequestMapping("/departments")
    public String departments(Model model){
        model.addAttribute("deps",departmentService.getAllDeps());
        return "departments";
    }

    /**
     * 添加部门
     * @param depname 部门名称
     * @param model
     * @return /admin/departments
     */
    @RequestMapping("/adddep")
    public String addDepartment(String depname,Model model){
        if (departmentService.addDep(depname)==-1) {model.addAttribute("error","该部门已存在");}
        return "forward:/admin/departments";
    }

    /**
     * 删除部门
     * @param depid 部门id
     * @return /admin/departments
     */
    @RequestMapping("/delDep")
    public String delDepartment(Integer depid){
        departmentService.Deldep(depid);
        return "redirect:/admin/departments";
    }

    /**
     * 更新部门信息
     * @param id 部门id
     * @param name 部门名称
     * @return JSON
     */
    @RequestMapping("/updatedep")
    @ResponseBody
    public String updatedep(Integer id,String name){
        Integer result = departmentService.updatedep(id,name);
        if(result==1){return "success";}
        else {return "error";}
    }
}
